﻿using System;
using System.Text;
using System.IO;

namespace VGSoftware.FileShutdownService
{
	public class Watcher
	{
		private static Watcher _instance;
		private static object _instanceLock = new object();

		private Watcher()
		{
		}

		public static Watcher Instance
		{
			get
			{
				if (_instance == null)
				{
					lock (_instanceLock)
					{
						if (_instance == null)
						{
							_instance = new Watcher();
						}
					}
				}
				return _instance;
			}
		}

		public void Start()
		{
			CreateFiles();
			CreateWatcher();
		}

		private void CreateWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Properties.Settings.Default.FileDirectory);
			fileSystemWatcher.EnableRaisingEvents = true;
			fileSystemWatcher.IncludeSubdirectories = false;
			fileSystemWatcher.Deleted += new FileSystemEventHandler(FileSystemWatcher_Deleted);
		}

		private void CreateFiles()
		{
			CreateFile(Settings.HibernateFile);
			CreateFile(Settings.RestartFile);
			CreateFile(Settings.ShutdownFile);
			CreateFile(Settings.StandbyFile);
		}

		private void CreateFile(string path)
		{
			FileInfo file = new FileInfo(path);
			if (!file.Exists)
			{
				file.Create();
			}
		}

		private void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
		{
			if (string.Compare(e.FullPath, Settings.HibernateFile, true) == 0)
			{
				CreateFile(Settings.HibernateFile);
				System.Windows.Forms.Application.SetSuspendState(System.Windows.Forms.PowerState.Hibernate, true, false);
			}
			else if (string.Compare(e.FullPath, Settings.RestartFile, true) == 0)
			{
				CreateFile(Settings.RestartFile);
				Shutdown.Restart();
			}
			else if (string.Compare(e.FullPath, Settings.ShutdownFile, true) == 0)
			{
				CreateFile(Settings.ShutdownFile);
				Shutdown.TurnOff();
			}
			else if (string.Compare(e.FullPath, Settings.StandbyFile, true) == 0)
			{
				CreateFile(Settings.StandbyFile);
				System.Windows.Forms.Application.SetSuspendState(System.Windows.Forms.PowerState.Suspend, true, false);
			}
		}
	}
}
